//
//  GBNetWorking+json.m
//  测试
//
//  Created by 李李善 on 2017/5/28.
//  Copyright © 2017年 森之源. All rights reserved.
//

#import "GBNetWorking+json.h"
#import "MABaseModel.h"

#if BaseClass ==1
#import "NSError+YU.h"

#endif

/*
 
 待废弃
 
 */
#ifndef IsSafeStringPlus
#define IsSafeStringPlus(a)             ((a)\
&&(![(a) isEqual:[NSNull null]]) &&((a).length>0)\
&&!([[NSString stringWithFormat:@"%@",(a)] isEqualToString:@"<null>"])\
&&!([[NSString stringWithFormat:@"%@",(a)] isEqualToString:@"(null)"]))
#endif

#ifndef TrToString
#define TrToString(args)[NSString stringWithFormat:@"%@",args]
#endif


#ifndef LongConvertToString
#define LongConvertToString(x) ((x)==-1?@"":[NSString stringWithFormat:@"%ld",((long)x)])
#endif

#ifndef IntToString
#define IntToString(x) ((x)==NOT_DEFINED?@"":[NSString stringWithFormat:@"%d",((int)x)])
#endif

#ifndef L2S
#define L2S(x) LongConvertToString(x)
#endif

#ifndef I2S
#define I2S(x) IntToString(x)
#endif
@implementation GBNetWorking (json)
+ (void (^)())checkHTTPStatusCodeRequestSucceed :(void(^)(BOOL success))_success{
    
    return ^(NSURLSessionDataTask* task,id responseObject) {
        
        [self checkHTTPStatusCodeWithModel:^(BOOL success, NSError *error,Class class) {
            
            _success(success);
            
        }](task,responseObject,nil);
        
    };
}


+ (void (^)())checkHTTPStatusCode :(void(^)(BOOL success,NSError *error))_success{
    
    return ^(NSURLSessionDataTask* task,id responseObject) {
        
        [self checkHTTPStatusCodeWithModel:^(BOOL success, NSError *error,Class class) {
            
            _success(success,error);
            
        }](task,responseObject,nil);
        
    };
}


+ (void (^)())checkHTTPStatusCodeWithModel :(void(^)(BOOL success,NSError *error,id model))success{
    
    return ^(NSURLSessionDataTask* task,NSDictionary * responseObject,Class aClass) {
        NSError *error;
        
        if (task!=nil) {
            NSLog(@"\n>>%@\n%@\n %@\n",task.response.URL.absoluteString,task.response,responseObject.description);
//            NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
//            NSInteger statusCode = [httpResponse statusCode];
//            NSLog(@"statusCode-->%@",@(statusCode));
        }
    
        
        if (![responseObject isKindOfClass:[NSDictionary class]])
        {
            return ;
        }
        NSInteger codeValue = [responseObject[kCode] integerValue];

//        if(aClass){
//            NSParameterAssert([aClass  isSubclassOfClass:[BaseModel class]]);
//        }
      
        
        id returnModel = nil;
        /**
         *  成功 解析数据
         */
        if (codeValue == 0) {
            id resultObject = responseObject[kResult];
            if (aClass&&resultObject) {
                if ([resultObject isKindOfClass:[NSDictionary class]]) {
                    
                    returnModel =[aClass mj_objectWithKeyValues:resultObject];
                }
                
                else if ([resultObject isKindOfClass:[NSArray class]]) {
                    returnModel = [aClass mj_objectArrayWithKeyValuesArray:resultObject];
                }
                else if ([resultObject isKindOfClass:[NSString class]]) {
                    returnModel = resultObject;
                    //responseDic = [task.response.URL.absoluteString jsonDictionary];
                }else{
                    NSLog(@"Warning：没有返回参数");
                }
            }
            else
            {
                   returnModel = @"请求成功";
            }
            
            success(true,error,returnModel);
            
            /**
             *  失败 解析错误提示 例如：这里202
             */
        }else{
            error = [NSError errorWithMsg:responseObject[kMessage]];
            
            success(false,error,nil);
//            [self checkHTTPErrorStatusCode:^(NSError *error) {
//                success(false,error,returnModel);
//            }](task,error);
        }
    };
}


+ (void (^)())checkHTTPErrorStatusCode :(void(^)(NSError *error))success{
    
    return ^(NSURLSessionDataTask* task, NSError *error) {
        NSHTTPURLResponse* httpResponse;
        if ([task isKindOfClass:[NSHTTPURLResponse class]]) {
            httpResponse = (NSHTTPURLResponse*)task;
        }else
        {
           httpResponse = (NSHTTPURLResponse*)task.response;
        }
        
        NSInteger errorCode = [httpResponse statusCode];
        
        NSString *msg;
        NSLog(@"URL-->%@\n",task.response.URL.absoluteString);
        NSLog(@"statusCode-->%@",@(errorCode));
        
        
        NSDictionary *messageDic = (NSDictionary*)task.response.URL.absoluteString;//httpResponse.allHeaderFields;//(NSDictionary*)response.responseString;
      
        
        if (![messageDic isKindOfClass:[NSDictionary class]]&&messageDic!=nil) {
         
           
            NSData *data = [(NSString*)task.response.URL.absoluteString dataUsingEncoding:NSUTF8StringEncoding];
            NSError *__autoreleasing error = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
             [NSDictionary new];
            messageDic =error!=nil?[NSDictionary new]:result;
        }
    


        if ([messageDic isKindOfClass:[NSDictionary class]]) {
            if (messageDic[kErrorCode]) {
                errorCode = [messageDic[kErrorCode] integerValue];
            }
            if(IsSafeStringPlus(TrToString(messageDic[kMessage]))){
                msg = messageDic[kMessage];
            }else{
                msg = HttpCodesDic()[L2S(errorCode)];
            }
        }
        
        switch (errorCode) {
                //程序处理
            case HTTPStatusCode_400:
            {
                NSLog(@"msg：%@",msg);
            }
                break;
                
                //特殊处理 添加此处
            case HTTPStatusCode_401:
            {
                
            }
                break;
                
                //错误 提示
            default:{
               
                error = [NSError errorWithCode:[NSString stringWithFormat:@"%@",@(errorCode)] msg:msg];
               
                success(error);
                
                if (IsSafeStringPlus(msg)) {
                   //[UIAlertView ShowInfo:msg time:1];
                }
            }
                break;
        }
    };
}
@end
